#!/usr/bin/python

import commands
import os
import time
import sys

num_hosts = int(sys.argv[1])

def launch(cmd, doprint=True):
    print cmd
    val = commands.getoutput(cmd)
    if doprint:
        print val
    return val

ssh_keyname = "dist-key"
aminame = 'ami-cef405a7'

launch('ec2-authorize default -p 20-25000')

launch('ec2-delete-keypair %s' % ssh_keyname)
key_value = launch('ec2-add-keypair %s' % ssh_keyname, False)
key_file = "%s.pem" % ssh_keyname
print 'created ssh private key'

try:
    os.unlink('%s'  % key_file)
except OSError:
    pass

f = open(key_file, 'w+')
f.write(key_value)
f.close()
launch ('chmod 600 %s ' % key_file)

print 'write ssh private key to %s' % key_file


instances = []

cmd = "ec2-run-instances -n %d %s --instance-type t1.micro -k %s" % (num_hosts, aminame, ssh_keyname)
val = launch(cmd)
for l in val.split('\n'):
    fields = l.split('\t')
    if fields[0] == 'INSTANCE':
        instance_id = fields[1]
        print 'instance %s' % (instance_id)
        instances.append(instance_id)

print 'INSTANCES: ', instances
term_string = '#!/bin/sh -x\nexec ec2-terminate-instances %s ' % (' '.join(instances))

terminate_file = 'stop_instances.sh'
f = open(terminate_file, 'w+')
f.write(term_string)
f.close()
launch ('chmod 777 %s ' % terminate_file)
print 'wrote terminate script: ./%s' % terminate_file

print 'sleeping 50 seconds to wait for instances to launch'
time.sleep(50)

cmd = 'ec2-describe-instances'

val = launch(cmd, False)

ip = None

instance_ips = {}

for x in val.split('\n'):
    for instance in instances:
        if instance in x:
            ip = x.split('\t')[3]
            print "found ip: %s" % ip
            instance_ips[instance] = ip

print instance_ips

i = 1
conf = ''
for instance in instance_ips:
    ip = instance_ips[instance]
    conf = conf + "%d %s 10002 20002\n" % (i, ip)
    i = i + 1

conf = conf.strip()

print 'configuration is:', conf

for instance in instance_ips:
    ip = instance_ips[instance]
    print '------------------- SETTING UP HOST: %s' % (ip)
    sshcmd = 'ssh -x -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no  -i %s ubuntu@%s ' % (key_file, ip)

    apt_update_cmd = 'sudo apt-get update'
    apt_get_cmd = 'sudo apt-get install -y openjdk-6-jre openjdk-6-jdk subversion inadyn tomcat6 tomcat6-user tomcat6-common'
    svn_checkout_cmd = 'svn checkout http://distbidsys.googlecode.com/svn/trunk/ distbidsys'

    cmds = '%s "%s && %s && %s " &>install.log &' % (sshcmd, apt_update_cmd, apt_get_cmd, svn_checkout_cmd)

    os.system(cmds)
    

print 'sleeping 100 seconds to wait for OS configuration'
time.sleep(100)
    
i = 1

for instance in instance_ips:
    ip = instance_ips[instance]
    print '------------------- BRINGING UP SERVER: %d at %s' % (i, ip)

    sshcmd = 'ssh -x -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no  -i %s ubuntu@%s ' % (key_file, ip)

    cmd = launch('%s "inadyn -u sashmit -p password -a dist%x.ath.cx --background --update_period 60000"' % (sshcmd, i))
    cmd = launch('%s "cd distbidsys; cd bidserver/src; javac *.java"' % sshcmd)
    cmd = launch('%s "cd distbidsys; jar cvf bidclient/webapps/bid/WEB-INF/lib/bidserver.jar bidserver/src/*.class"' % sshcmd)
    cmd = launch('%s "echo \'%s\' > /tmp/bidServer.conf"' % (sshcmd, conf))
    os.system('%s "cd distbidsys; java bidserver.src.BidServer %d" &' % (sshcmd, i))
    cmd = launch('%s "cd distbidsys/bidclient/webapps/bid/WEB-INF/classes; ./recompile.sh "' % sshcmd)
    cmd = launch('%s "cd distbidsys/bidclient/bin; ./startup.sh"' % sshcmd)

    i = i + 1

i = 1
for instance in instance_ips:
    cmd = launch('firefox http://dist%x.ath.cx:8081/bid' % i)
    i = i + 1

    
#cmd = launch('ec2-terminate-instances %s' % instance_id)




